package com.yystudy.system.controller;

import com.yystudy.common.result.Result;
import com.yystudy.common.result.ResultCodeEnum;
import com.yystudy.common.utils.JwtHelper;
import com.yystudy.model.system.SysUser;
import com.yystudy.model.vo.LoginVo;
import com.yystudy.system.handler.CustomException;
import com.yystudy.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "用户登录接口")
@RequestMapping("/admin/system/index")
public class IndexController {


    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录接口
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录接口")
    public Result login(@RequestBody LoginVo loginVo){
        SysUser sysUser = sysUserService.getByUsername(loginVo.getUsername());
        //是否有该用户
        if(null == sysUser) {
            throw new CustomException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        //验证密码
        if(!DigestUtils.md5DigestAsHex(loginVo.getPassword().getBytes()).equals(sysUser.getPassword())) {
            throw new CustomException(ResultCodeEnum.PASSWORD_ERROR);
        }
        //用户账号是否停用
        if(sysUser.getStatus().intValue() == 0) {
            throw new CustomException(ResultCodeEnum.ACCOUNT_STOP);
        }

        Map<String, Object> map = new HashMap<>();
        //验证成功，用用户名和用户id封装进JWT中返回
        String token = JwtHelper.createToken(Long.parseLong(sysUser.getId()), sysUser.getUsername());
        map.put("token", token);
        return Result.ok(map);
    }


    /**
     * 登录用户信息接口
     * 用户名，用户角色，用户头衔
     * 用户的菜单权限，用户的按钮权限
     * @return
     */
    @GetMapping("/info")
    @ApiOperation(value = "登录用户信息接口")
    public Result info(HttpServletRequest request){
        String token = request.getHeader("token");
        String username = JwtHelper.getUsername(token);

        Map<String,Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }


    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登录")
    public Result logout(){
        return Result.ok();
    }



}
